<template>
	<image :mode="node.attr.mode" :lazy-load="node.attr.lazyLoad" :class="node.classStr" :style="newStyleStr || node.styleStr"
	 :data-src="node.attr.src" :src="node.attr.src" @tap="wxParseImgTap" @load="wxParseImgLoad" />
</template>

<script>
	export default {
		name: 'wxParseImg',
		data() {
			return {
				newStyleStr: '',
				preview: true,
			};
		},
		props: {
			node: {
				type: Object,
				default () {
					return {
						attr: {
							padding: 0,
							mode: '',
							lazyLoad: false,
							src: '',
						},
						styleStr: '',
						classStr: '',
					};
				},
			},
		},
		methods: {
			wxParseImgTap(e) {
				if (!this.preview) return;
				const {
					src
				} = e.target.dataset;
				if (!src) return;
				this.node.$host.preview(src, e);
			},

			// 图片视觉宽高计算函数区
			wxParseImgLoad(e) {
				const {
					src
				} = e.target.dataset;
				if (!src) return;
				const {
					width,
					height
				} = e.mp.detail;
				const recal = this.wxAutoImageCal(width, height);
				let {
					imageHeight,
					imageWidth
				} = recal;
				let {
					padding,
					mode
				} = this.node.attr;
				let {
					styleStr
				} = this.node;

				//修复BUG，错误使用upx单位导致微信小程序中图片不能正常显示，修复padding,styleStr为NAN的错误
				styleStr = styleStr || "";
				padding = padding || 0;

				imageHeight = Math.round(this.node.$screen.width / 750.0 * imageHeight);
				imageWidth = Math.round(this.node.$screen.width / 750.0 * imageWidth);
				padding = Math.round(this.node.$screen.width / 750.0 * padding);

				//       const imageHeightStyle = mode === 'widthFix' ? '' : `height: ${imageHeight}upx;`;
				//       this.newStyleStr = `${styleStr}; ${imageHeightStyle}; width: ${imageWidth}upx; padding: 0 ${+padding}upx;`;
				const imageHeightStyle = mode === 'widthFix' ? '' : `height: ${imageHeight}px;`;
				this.newStyleStr = `${styleStr}; ${imageHeightStyle}; width: ${imageWidth}px; padding: ${padding}px;`;
			},
			// 计算视觉优先的图片宽高
			wxAutoImageCal(originalWidth, originalHeight) {
				// 获取图片的原始长宽
				const {
					padding
				} = this.node.attr;
				const windowWidth = this.node.$screen.width - (2 * padding);
				const results = {};

				if (originalWidth < 60 || originalHeight < 60) {
					const {
						src
					} = this.node.attr;
					this.node.$host.removeImageUrl(src);
					this.preview = false;
				}

				// 判断按照那种方式进行缩放
				if (originalWidth > windowWidth) {
					// 在图片width大于手机屏幕width时候
					results.imageWidth = windowWidth;
					results.imageHeight = windowWidth * (originalHeight / originalWidth);
				} else {
					// 否则展示原来的数据
					results.imageWidth = originalWidth;
					results.imageHeight = originalHeight;
				}

				return results;
			},
		},
	};
</script>
